import { Component, ElementRef, Renderer2, TemplateRef, ViewChild, ViewContainerRef } from '@angular/core';
import {MatIconModule} from '@angular/material/icon';
import {Overlay, OverlayConfig, OverlayModule, OverlayRef} from '@angular/cdk/overlay';
import {MatCardModule} from '@angular/material/card';
import {CdkTreeModule, FlatTreeControl} from '@angular/cdk/tree';
import {MatProgressBarModule} from '@angular/material/progress-bar'; 
import {MatButtonModule} from '@angular/material/button';
import {MatTreeModule} from '@angular/material/tree';
import { auth, file, fileInfoBaseDto, folder, QueryDto } from 'ispace.core.main';
import { TaskbarMenuItemCmpComponent } from "../taskbar-menu-item-cmp/taskbar-menu-item-cmp.component";
import { DynamicDataSource } from './dynamicDataSource';
import { DynamicFlatNode } from './dynamicFlatNode';
import { DynamicDatabase } from './dynamicDatabase';
 import { A11yModule } from '@angular/cdk/a11y'; // 导入无障碍模块
import {MatMenuModule} from '@angular/material/menu';
import { CdkMenuModule } from '@angular/cdk/menu';
import { TaskbarMenuItemDto } from '../taskbar-menu-item-cmp/taskbar-menu-item-dto';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { DriverOperationDto } from 'ispace_de';
import { DriveEnginService } from '../../service/drive-engin.service';
import { CdkTrapFocus } from '@angular/cdk/a11y';
import { TemplatePortal } from '@angular/cdk/portal';
import { SelectionBoxCmpComponent } from '../selection-box-cmp/selection-box-cmp.component';
@Component({
  selector: 'app-taskbar-menu-cmp',
  standalone: true,
  imports: [MatIconModule, CdkTrapFocus,A11yModule, OverlayModule, MatCardModule, MatTreeModule, MatButtonModule, MatProgressBarModule, TaskbarMenuItemCmpComponent,MatMenuModule,CdkMenuModule, CommonModule, FormsModule],
  templateUrl: './taskbar-menu-cmp.component.html',
  styleUrl: './taskbar-menu-cmp.component.sass'
})
export class TaskbarMenuCmpComponent { 

  basePath = "Desktop/.ispace/menu";
  iconUrl = "assets/icon/unknown.png";
  @ViewChild('taskbar_menu_overlay') 
  taskbar_menu_overlay!:OverlayRef ;

  @ViewChild('trigger') trigger!: ElementRef;
  @ViewChild('panelTemplate') panelTemplate!: TemplateRef<any>;
 
  private overlayRef!: OverlayRef;
  private globalClickListener!: () => void;
  
  triggerMenu() {
    this.isOpen = !this.isOpen;
    if(this.isOpen) {
       this.open();
    } else {
      this.close();
    }
  }

open() {
    // 1. 配置 Overlay
    const config = new OverlayConfig({
      positionStrategy: this.overlay.position()
        .flexibleConnectedTo(
          this.trigger
        )
        .withPositions([
      {
        originX: 'start',       // 按钮左侧
        originY: 'top',         // 按钮顶部（关键点）
        overlayX: 'start',      // 面板左侧对齐按钮左侧
        overlayY: 'bottom'      // 面板底部对齐按钮顶部（向上展开）
        ,offsetY: -60
      }
    ])
    .withPush(false)// 禁用自动位置调整（强制显示在指定位置）方位移）
    ,
      hasBackdrop: false, // 不显示背景层
      scrollStrategy: this.overlay.scrollStrategies.close() // 滚动时自动关闭
    });
 
    // 2. 创建 Overlay 并附加模板
    this.overlayRef = this.overlay.create(config);
    const portal = new TemplatePortal(this.panelTemplate, this.viewContainerRef);
    this.overlayRef.attach(portal);
 
    
    // 3. 添加全局点击监听
    this.globalClickListener = this.renderer.listen(
      'document',
      'click',
      (event: MouseEvent) => { 
        // 面板上的点击不关闭
        if (this.overlayRef.overlayElement.contains(event.target as Node)) {
          return;
        }
 
        // 指定对象上的点击不关闭
        const classList  = ["cdk-overlay-backdrop","cdk-overlay-transparent-backdrop","mat-mdc-menu-content","menu-item","taskbar-menu-pannel"];
        let targetList =event.target as any;
        for(let i=0;i<targetList.classList.length;i++) {
          let className = targetList.classList[i];
          if(classList.includes(className))
            {
              return;
            }
          }

        // 其他区域点击关闭 
        this.close();
      }
    );
  }
 
  close() {
    this.isOpen = false;
    if (this.overlayRef && this.overlayRef.hasAttached()) {
      this.overlayRef.detach();
      this.overlayRef.dispose();
      if (this.globalClickListener) {
        this.globalClickListener(); // 移除监听
        this.globalClickListener = null!;
      }
      this.expandList = [];
    }
  }

  removeItem(data: TaskbarMenuItemDto) {
    let path = data.path.replace("/" + data.name, "");
    if(data.type == "folder") { 
      folder.remove(path, data.name).subscribe(s => {
      this.load();
      }, e => {
        console.error(e);
      })
    }
    else {
      file.remove(path, data.name).subscribe(s => {
       this.load();
      }, e => {
        console.error(e);
      })
    }
  
  } 
   
logout() {
  auth.logout();
  window.location.reload();
}
 
  // all
  isOpen = false;

  // 展开项列表
  expandList:string[] = [];
  expandedChange(data: DynamicFlatNode) {
    if (this.expandList.includes(data.item.id)) {
      this.expandList.splice(this.expandList.indexOf(data.item.id), 1);
    } else {
      this.expandList.push(data.item.id);
    }
  }

  // 用户区
  userName = '';

  // 列表区
  treeControl: FlatTreeControl<DynamicFlatNode>;
  dataSource: DynamicDataSource;
  getLevel = (node: DynamicFlatNode) => node.level;
  isExpandable = (node: DynamicFlatNode) => node.expandable;
  hasChild = (_: number, _nodeData: DynamicFlatNode) => _nodeData.expandable;

  constructor(private database: DynamicDatabase,private driveEngine: DriveEnginService,private overlay: Overlay,
    private viewContainerRef: ViewContainerRef,
    private renderer: Renderer2) {
    this.load_templates();

    // 用户区
    this.userName = auth.getUserInfo().name??"未登录";

    // 列表区
    this.treeControl = new FlatTreeControl<DynamicFlatNode>(this.getLevel, this.isExpandable);
    this.dataSource = new DynamicDataSource(this.treeControl, database);
    this.load();

    this.dataSource.dataChange.subscribe(s => {
        this.expandList.forEach(s => {
        let node = this.dataSource.data.find(s1 => s1.item.id == s);
        if(node) {
          this.treeControl.expand(node);
        } 
      })
    })

  }

  load() {
    this.database.initialData().then((s) => { 
      s.forEach(s => {
         s.level = 1;
      })
      this.dataSource.data = s; 
    }); 

    this.init_sourceManagerOpen(); 
  }
 
  isCanPasteFlag = false;

  async contextMenuOpened(event: any) {
    this.isCanPasteFlag = await this.isCanPaste();
  }

  isCanPaste = ()=>{ 
    return navigator.clipboard.readText().then(s => { 
    if(s?.length <=0) {
      return false;
    }
    if(s.startsWith("$ispace copy") == false && s.startsWith("$ispace shear") == false) {
      return false; 
    } 
      return true;
    }).catch(e=>{ 
      console.error(e);
      return false;
    });
  }
  
  paste() { 
    navigator.clipboard.readText().then(s => {
       
      let info = s.split(" "); 
      let path = info[3]
      let fileType = info[4];
      let type = info[1];
      let nameS = path.split("/");
      let name = nameS[nameS.length - 1];

      if (fileType == "file") {
        if (type == "copy") {

          file.copy(path, this.basePath +"/" + name).subscribe(s => {
            this.load();
          }, e => {
          console.error(e);
          });
        }
        if (type == "shear") {
          file.move(path, this.basePath +"/" + name).subscribe(s => {
            this.load();
          }, e => {
            console.error(e);
          }
          ) 
        }
      }

      if (fileType == "folder") {
        if (type == "copy") {
          folder.copy(path, this.basePath +"/" + name).subscribe(s => {
            this.load();
          }, e => { 
            console.error(e);
          });
        }
        if (type == "shear") {
          folder.move(path, this.basePath +"/" + name).subscribe(s => {
            this.load();
          }, e => { 
            console.error(e);
          }
          ) 
        }
      } 
    }).catch(e=>{ 
      console.error(e);
    });
  }

  createFolder(node?: DynamicFlatNode) { 
 
    let level = 1;
    let indexPath = this.basePath;
    if(node) {
      level = node.level+1;
      indexPath = node.item.path;
    }
 
    let maxIndex = 0; 
    this.dataSource.data.filter(s => s.level == level && s.item.type == "folder" && s.item.name.startsWith("新建文件夹"))
      .forEach(s => {
         let indexStr = s.item.name.replace("新建文件夹", "").trim();
         let index = Number(indexStr);
         if (index > maxIndex) {
           maxIndex = index;
         }
      });
      maxIndex++;
    let folderName = "新建文件夹" + maxIndex;
   folder.create(indexPath, folderName).subscribe(s=>{
      this.load();
   }, e=>{
     console.error(e);
   })
  }

  /*** 新建文件 ***/
  createFile_basePath = "Desktop/.ispace/new_decument_template";
  createFile_templates:fileInfoBaseDto[] = [];

  load_templates() {
    if (this.createFile_templates.length > 0) {
       this.createFile_templates = [];
    }
    let query = new QueryDto();
    query.path = this.createFile_basePath;
    folder.children(query).subscribe(s => {
      this.createFile_templates = s.filter(s => !s.isDir);
    })
  }
  
  createFile(template: fileInfoBaseDto,node?: DynamicFlatNode) {

 
    let level = 1;
    let indexPath = this.basePath;
    if(node) {
      level = node.level+1;
      indexPath = node.item.path;
    }

    // 名称 和 后缀
    let data = template.name!.split(".");
    let name = data[0]; 
    let ext = data[1]; 

    let maxIndex = 0;
    this.dataSource.data.filter(s => s.level == level &&  s.item.type == "file" && s.item.name.endsWith('.'+ext) && s.item.name.startsWith(name))
      .forEach(s => { 
         let indexStr = s.item.name.replace(name!, "").replace('.'+ext, "").trim();
         let index = Number(indexStr);
         if (index > maxIndex) {
           maxIndex = index;
         }
      });
      maxIndex++;
    let createName = name + maxIndex + '.' + ext;  
     file.copy(this.createFile_basePath + "/" + template.name, indexPath + "/" + createName).subscribe(s=>{
      this.load();
    }, e=>{
      console.error(e);
    })
  }

  ext_operations: DriverOperationDto[] = [];
  init_sourceManagerOpen() { 
    this.ext_operations=  this.driveEngine.getOperations(this.basePath,true); 
      let op =  this.ext_operations.find(s=>s.driverId==1 && s.id==1);
      if(!op)
        {
          console.error("not found");
          return;
        }
      this.iconUrl= this.driveEngine.driveEngine.drivers.value.find(s=>s.id==op!.driverId)?.fileIconUrl??"";
  }
  
  ext_operation_execute(operation: DriverOperationDto) {
    this.driveEngine.execute(operation.driverId,operation.id,this.basePath,"folder",{ name: this.basePath, type: "folder",iconUrl:this.iconUrl });
  } 
}
